"use client"

import { useEffect, useRef } from "react"
import { useRouter } from "next/navigation"
import { useAuth } from "@/components/auth-provider"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"

export default function LoginPage() {
  const intervalRef = useRef<NodeJS.Timeout>()
  const { login, isAuthenticated } = useAuth()
  const router = useRouter()

  useEffect(() => {
    if (isAuthenticated) {
      router.push("/")
      return
    }

    // 获取二维码 ticket
    fetch("http://localhost:8091/api/v1/login/weixin_qrcode_ticket")
      .then((response) => response.json())
      .then((data) => {
        if (data.code === "0000") {
          const ticket = data.data
          const qrCodeImg = document.getElementById("qr-code-img") as HTMLImageElement
          qrCodeImg.src = `https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${ticket}`

          // 开始轮询检查登录状态
          intervalRef.current = setInterval(() => {
            checkLoginStatus(ticket)
          }, 3000)
        } else {
          console.error("获取二维码 ticket 失败:", data.info)
        }
      })
      .catch((error) => {
        console.error("请求失败:", error)
      })

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current)
      }
    }
  }, [router, isAuthenticated])

  const checkLoginStatus = (ticket: string) => {
    fetch(`http://localhost:8091/api/v1/login/check_login?ticket=${ticket}`)
      .then((response) => response.json())
      .then((data) => {
        if (data.code === "0000") {
          console.info("login success")
          if (intervalRef.current) {
            clearInterval(intervalRef.current)
          }
          login(data.data)
          router.push("/")
        } else {
          console.info("login wait")
        }
      })
      .catch((error) => {
        console.error("请求失败:", error)
      })
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/10 to-secondary/10 p-4">
      <Card className="w-full max-w-md">
        <CardHeader className="text-center">
          <CardTitle className="text-2xl">欢迎登录</CardTitle>
          <CardDescription>请使用微信扫描二维码登录</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex justify-center p-4">
            <div className="w-64 h-64 bg-secondary flex items-center justify-center rounded-lg overflow-hidden">
              <img id="qr-code-img" alt="微信登录二维码" className="max-w-full max-h-full" />
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}

